package com.example.demo.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.example.demo.dto.User;
import com.example.demo.jwt.JWTConstant;
import com.example.demo.jwt.JWTUtil;
import com.example.demo.mapper.SysUserMapper;
import com.example.demo.redis.RedisClient;
import com.example.demo.result.JsonResult;
import com.example.demo.service.LoginService;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author zhanpengguo
 * @date 2019-07-04 13:55
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    RedisClient redisClient;

    @Value("${refreshTokenExpireTime}")
    String refreshTokenExpireTime;

    @Override
    public JsonResult jwtLogin(String username, String password) {
        Assert.notNull(username,"用户名不能为空");
        Assert.notNull(password,"密码不能为空");

        User user = sysUserMapper.findByName(username);

        if (user == null){
            return new JsonResult(new Throwable("用户不存在"));
        }
        if (SecureUtil.md5(password).equals(user.getPassword())){
            String currentTimeMillis = String.valueOf(System.currentTimeMillis());
            String token = JWTUtil.sign(username,currentTimeMillis);
            if (token != null){
                // 设置RefreshToken，时间戳为当前时间戳，直接设置即可(不用先删后设，会覆盖已有的RefreshToken)
                redisClient.set(JWTConstant.getRefreshTokenKey(username),currentTimeMillis,Integer.parseInt(refreshTokenExpireTime));
                return new JsonResult(token);
            }
        }
        return new JsonResult(new Throwable("密码不正确"));
    }

}
